﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TravelAgency.DAL;
using System.IO;

namespace TravelAgency.AspNet.Agents
{
    /// <summary>
    /// Summary description for DisplayPhoto
    /// </summary>
    public class DisplayPhoto : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/png";

            if(context.Request.QueryString["photoId"] == string.Empty)
            {
                string palmLogoPath = context.Server.MapPath("~/Images/PalmLogo.png");
                FileStream palmLogo = File.OpenRead(palmLogoPath);
                context.Response.OutputStream.Write(this.GetFileStreamBytes(palmLogo), 0, (int)palmLogo.Length);
            }

            try
            {
                string photoIdString = context.Request.QueryString["photoId"];
                int photoId = int.Parse(photoIdString);
                TravelAgencyDAO dao = new TravelAgencyDAO();
                Photo requestedPhoto = dao.GetPhotoByPhotoId(photoId);

                context.Response.OutputStream.Write(
                    requestedPhoto.PhotoContent, 0, requestedPhoto.PhotoContent.Length);
            }
            catch
            {
                new ArgumentException("Invalid query string.");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private byte[] GetFileStreamBytes(FileStream fileStream)
        {
            byte[] fileStreamBytes = new byte[fileStream.Length];
            int totalBytesRead = 0;
            int bytesRead = fileStream.Read(fileStreamBytes, 0, (int)fileStream.Length - totalBytesRead);

            while (bytesRead != 0)
            {
                totalBytesRead += bytesRead;
                bytesRead = fileStream.Read(
                    fileStreamBytes, totalBytesRead, (int)fileStream.Length - totalBytesRead);
            }

            return fileStreamBytes;
        }
    }
}